package com.gomtel.smartdevice.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.api.BleManager;
import com.gomtel.smartdevice.api.MessageManager;
import com.gomtel.smartdevice.api.bean.AFResponse;
import com.gomtel.smartdevice.api.bean.BatteryFirmwareVersionResponse;
import com.gomtel.smartdevice.api.bean.BpResponse;
import com.gomtel.smartdevice.api.bean.GoalResponse;
import com.gomtel.smartdevice.api.bean.HistoryEndResponse;
import com.gomtel.smartdevice.api.bean.NotificationResponse;
import com.gomtel.smartdevice.api.bean.OrderResponse;
import com.gomtel.smartdevice.api.bean.ProfileBean;
import com.gomtel.smartdevice.api.bean.StepResponse;
import com.gomtel.smartdevice.api.bean.TotalResponse;
import com.gomtel.smartdevice.init.SmartDeviceManager;
import com.gomtel.smartdevice.interfaces.MacUtils;
import com.gomtel.smartdevice.interfaces.OnCallbackListener;
import com.gomtel.smartdevice.interfaces.OnConnectListener;
import com.gomtel.smartdevice.interfaces.OnFotaCallbackListener;
import com.gomtel.smartdevice.interfaces.OnScannerListener;
import com.gomtel.smartdevice.interfaces.Progress;
import com.gomtel.smartdevice.utils.FileUtils;
import com.gomtel.smartdevice.utils.ToastUtil;
import com.gomtel.smartdevice.bt.ble.BLEDevice;
import java.io.File;

public class MainDemoActivity extends Activity {

    Button btn_connect;
    Button btn_verification;
    Button btn_synctime;
    Button btn_bind;
    Button btn_unbind;
    Button btn_getDeviceInfo;
    Button btn_profile;
    Button btn_getHistoryStep;
    Button btn_bp;
    Button btn_fota;
    Button btn_af;
    Button btn_history_af;
    TextView logView;

    boolean isUnbind = false;
    private static final int FILE_SELECT_CODE = 0;
    private static final String MAC = "C3:07:05:A8:05:0E";
    private ToastUtil toastUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_demo);
        SmartDeviceManager.getInstance().init(this);
        MessageManager.getInstance().register();
        toastUtil = new ToastUtil(this);
        btn_connect = (Button) findViewById(R.id.btn_connect);
        btn_verification = (Button) findViewById(R.id.btn_verification);
        btn_synctime = (Button) findViewById(R.id.btn_synctime);
        btn_bind = (Button) findViewById(R.id.btn_bind);
        btn_unbind = (Button) findViewById(R.id.btn_unbind);
        btn_getDeviceInfo = (Button) findViewById(R.id.btn_getDeviceInfo);
        btn_profile = (Button) findViewById(R.id.btn_profile);
        btn_getHistoryStep = (Button) findViewById(R.id.btn_getHistoryStep);
        btn_bp = (Button) findViewById(R.id.btn_bp);
        btn_fota = (Button) findViewById(R.id.btn_fota);
        btn_af = (Button) findViewById(R.id.btn_af);
        btn_history_af = (Button) findViewById(R.id.btn_history_af);

        logView = (TextView) findViewById(R.id.txt);
        logView.setMovementMethod(ScrollingMovementMethod.getInstance());
        listener();
        getBack();
        BleManager.getInstance().scan(1, new OnScannerListener() {
            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onNext(BLEDevice a) {

            }
        });
    }

    public void listener() {
        btn_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BleManager.getInstance().connect(MAC, new OnConnectListener() {
                    @Override
                    public void onSuccess() {
                        toastUtil.showToast("已连接上");
                        refreshLogView("已连接上");
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                        toastUtil.showToast("连接失败");
                        refreshLogView("连接断开");
                    }

                    @Override
                    public void onTimeout() {
                        toastUtil.showToast("连接超时");
                        refreshLogView("连接超时");
                    }
                });
            }
        });

        btn_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendBind(MacUtils.getMac(MainDemoActivity.this));
            }
        });

        btn_unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isUnbind = true;
                MessageManager.getInstance().sendUnbind(MacUtils.getMac(MainDemoActivity.this));
            }
        });

        btn_verification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendValidation(MacUtils.getMac(MainDemoActivity.this));
            }
        });

        btn_synctime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendTime();
            }
        });

        btn_getDeviceInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendSystemInfo();
            }
        });

        btn_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProfileBean profileBean = new ProfileBean();
                profileBean.setAge(30);
                profileBean.setGender(1);
                profileBean.setHeight(170);
                profileBean.setWeight(58);
                profileBean.setArmLength(73);
                MessageManager.getInstance().sendPersonInfo(profileBean);
                //获取用户信息请用MessageManager.getInstance().sendSystemInfo();
                //接收用户信息,请用 MessageManager.getInstance().setProfileListener(new OnCallbackListener<ProfileBean>())
            }
        });

        btn_getHistoryStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendHistoryStep();
            }
        });

        btn_bp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendTriggerMeasurement(MessageManager.MeasurementID_BP, MessageManager.MeasurementID_STATUS_START);
            }
        });

        btn_fota.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showFileChooser();
            }
        });
        btn_af.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendTriggerMeasurement(MessageManager.MeasurementID_AF, MessageManager.MeasurementID_STATUS_START);
            }
        });
        btn_history_af.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MessageManager.getInstance().sendHistoryAF();
            }
        });

    }

    public void getBack() {
        MessageManager.getInstance().orderResponse(new OnCallbackListener<OrderResponse>() {
            @Override
            public void onCallback(OrderResponse orderResponse) {
                if (orderResponse.order.equals("D2") && orderResponse.status.equals("00")) {
                    if (isUnbind) {
                        isUnbind = false;
                        BleManager.getInstance().disconnect();
                    }
                }
                refreshLogView("握手回复 ： order = " + orderResponse.order + ", status = " + orderResponse.status);
            }
        });

        MessageManager.getInstance().setBatteryAndFirmwareVersionListener(new OnCallbackListener<BatteryFirmwareVersionResponse>() {
            @Override
            public void onCallback(BatteryFirmwareVersionResponse batteryFirmwareVersionResponse) {
                refreshLogView("Battery = " + batteryFirmwareVersionResponse.getBattery() + ", FirmwareVersion = " + batteryFirmwareVersionResponse.getFirmwareVersion());
            }
        });

        MessageManager.getInstance().setTotalStepListener(new OnCallbackListener<TotalResponse>() {
            @Override
            public void onCallback(TotalResponse totalResponse) {
                refreshLogView("TotalStep = " + totalResponse.getTotalStep() + ", TotalCalories = " + totalResponse.getTotalCalories());
            }
        });

        MessageManager.getInstance().setNotificationListener(new OnCallbackListener<NotificationResponse>() {
            @Override
            public void onCallback(NotificationResponse notificationResponse) {
                refreshLogView("daily = " + notificationResponse.daily + ", sedentary = " + notificationResponse.sedentary +
                        ",wearingLoose = " + notificationResponse.wearingLoose + ", phoneRang = " + notificationResponse.phoneRang +
                        ",exercise = " + notificationResponse.exercise);
            }
        });

        MessageManager.getInstance().setGoalListener(new OnCallbackListener<GoalResponse>() {
            @Override
            public void onCallback(GoalResponse goalResponse) {
                refreshLogView("stepCountGoal = " + goalResponse.getStepCountGoal() + ", heartRateGoal = " + goalResponse.getHeartRateGoal() +
                        ",continue_Time = " + goalResponse.getContinue_Time() + ", duration = " + goalResponse.getDuration() +
                        ",calorie = " + goalResponse.getCalorie());
            }
        });

        MessageManager.getInstance().setProfileListener(new OnCallbackListener<ProfileBean>() {
            @Override
            public void onCallback(ProfileBean profileBean) {
                refreshLogView("age = " + profileBean.getAge() + ", gender = " + profileBean.getGender() +
                        ",height = " + profileBean.getHeight() + ", weight = " + profileBean.getWeight() +
                        ",armLength = " + profileBean.getArmLength());
            }
        });

        MessageManager.getInstance().setStepListener(new OnCallbackListener<StepResponse>() {
            @Override
            public void onCallback(StepResponse stepResponse) {
                refreshLogView("step = " + stepResponse.getTotalStepCount() + ", runStep = " + stepResponse.getRunStepCount() +
                        ",walkDuration = " + stepResponse.getTotalWalkDuration() + ", RunDuration = " + stepResponse.getTotalRunDuration() +
                        ",calorie = " + stepResponse.getCalorie());
            }
        });

        MessageManager.getInstance().setBpListener(new OnCallbackListener<BpResponse>() {
            @Override
            public void onCallback(BpResponse bpResponse) {
                refreshLogView("systolic = " + bpResponse.getSystolic() + ", diastolic = " + bpResponse.getDiastolic() +
                        ",hr = " + bpResponse.getHr() + ", pwtt = " + bpResponse.getPwtt());
            }
        });

        MessageManager.getInstance().setHistoryEndListener(new OnCallbackListener<HistoryEndResponse>() {
            @Override
            public void onCallback(HistoryEndResponse historyEndResponse) {
                refreshLogView("command = " + historyEndResponse.getCommand() + ", featureID = " + historyEndResponse.getFeatureID() +
                        ",response = " + historyEndResponse.getResponse());
            }
        });

        MessageManager.getInstance().setFotaListener(new OnFotaCallbackListener() {
            @Override
            public void onCompleted() {
                refreshLogView("Fota Completed ");
            }

            @Override
            public void onError(Throwable e) {
                refreshLogView("Fota error = " + e.getMessage());
            }

            @Override
            public void onNext(Progress progress) {
                refreshLogView("Fota progress = " + progress.percent);
            }
        });

        MessageManager.getInstance().setAFListener(new OnCallbackListener<AFResponse>() {
            @Override
            public void onCallback(AFResponse afResponse) {
                refreshLogView("时间戳 = " + afResponse.getUnixTimestamp() + ", ppi = " + afResponse.getPpi() +
                        ",状态 = " + afResponse.getState());
            }
        });
    }

    public void refreshLogView(String msg) {
        logView.append("\n-----------------------------");
        logView.append("\n" + msg);
        int offset = logView.getLineCount() * logView.getLineHeight();
        if (offset > logView.getHeight()) {
            logView.scrollTo(0, offset - logView.getHeight());
        }
    }

    private void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            startActivityForResult(Intent.createChooser(intent, "Select MainZhenBean File to Upload"), FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(this, "Please install MainZhenBean File Manager.", Toast.LENGTH_SHORT).show();
        }
    }

    private static final String TAG = MainDemoActivity.class.getSimpleName();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    try {
                        Uri uri = data.getData();
                        String path = FileUtils.getPath(this, uri);
                        Log.d(TAG, "File Path: " + path);
                        File file = null;
                        if (path != null) {
                            file = new File(path);
                        }
                        MessageManager.getInstance().startFota(file, MAC);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        BleManager.getInstance().colse();
        BleManager.getInstance().disconnect();
        MessageManager.getInstance().unRegister();
        super.onDestroy();
    }
}
